{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# An Introduction to SageMaker Random Cut Forests\n",
    "\n",
    "***Unsupervised anomaly detection on timeseries data a Random Cut Forest algorithm.***\n",
    "\n",
    "---\n",
    "\n",
    "1. [Introduction](#Introduction)\n",
    "1. [Setup](#Setup)\n",
    "1. [Training](#Training)\n",
    "1. [Inference](#Inference)\n",
    "1. [Epilogue](#Epilogue)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction\n",
    "***\n",
    "\n",
    "Amazon SageMaker Random Cut Forest (RCF) is an algorithm designed to detect anomalous data points within a dataset. Examples of when anomalies are important to detect include when website activity uncharactersitically spikes, when temperature data diverges from a periodic behavior, or when changes to public transit ridership reflect the occurrence of a special event.\n",
    "\n",
    "In this notebook, we will use the SageMaker RCF algorithm to train an RCF model on the Numenta Anomaly Benchmark (NAB) NYC Taxi dataset which records the amount New York City taxi ridership over the course of six months. We will then use this model to predict anomalous events by emitting an \"anomaly score\" for each data point. The main goals of this notebook are,\n",
    "\n",
    "* to learn how to obtain, transform, and store data for use in Amazon SageMaker;\n",
    "* to create an AWS SageMaker training job on a data set to produce an RCF model,\n",
    "* use the RCF model to perform inference with an Amazon SageMaker endpoint.\n",
    "\n",
    "The following are ***not*** goals of this notebook:\n",
    "\n",
    "* deeply understand the RCF model,\n",
    "* understand how the Amazon SageMaker RCF algorithm works.\n",
    "\n",
    "If you would like to know more please check out the [SageMaker RCF Documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/randomcutforest.html)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Setup\n",
    "\n",
    "***\n",
    "\n",
    "*This notebook was created and tested on an ml.m4.xlarge notebook instance.*\n",
    "\n",
    "Our first step is to setup our AWS credentials so that AWS SageMaker can store and access training data and model artifacts. We also need some data to inspect and to train upon."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Select Amazon S3 Bucket\n",
    "\n",
    "We first need to specify the locations where we will store our training data and trained model artifacts. ***This is the only cell of this notebook that you will need to edit.*** In particular, we need the following data:\n",
    "\n",
    "* `bucket` - An S3 bucket accessible by this account.\n",
    "* `prefix` - The location in the bucket where this notebook's input and output data will be stored. (The default value is sufficient.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "isConfigCell": true
   },
   "outputs": [],
   "source": [
    "import boto3\n",
    "import botocore\n",
    "import sagemaker\n",
    "import sys\n",
    "\n",
    "\n",
    "bucket = ''   # <--- specify a bucket you have access to\n",
    "prefix = 'sagemaker/rcf-benchmarks'\n",
    "execution_role = sagemaker.get_execution_role()\n",
    "\n",
    "\n",
    "# check if the bucket exists\n",
    "try:\n",
    "    boto3.Session().client('s3').head_bucket(Bucket=bucket)\n",
    "except botocore.exceptions.ParamValidationError as e:\n",
    "    print('Hey! You either forgot to specify your S3 bucket'\n",
    "          ' or you gave your bucket an invalid name!')\n",
    "except botocore.exceptions.ClientError as e:\n",
    "    if e.response['Error']['Code'] == '403':\n",
    "        print(\"Hey! You don't have permission to access the bucket, {}.\".format(bucket))\n",
    "    elif e.response['Error']['Code'] == '404':\n",
    "        print(\"Hey! Your bucket, {}, doesn't exist!\".format(bucket))\n",
    "    else:\n",
    "        raise\n",
    "else:\n",
    "    print('Training input/output will be stored in: s3://{}/{}'.format(bucket, prefix))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Obtain and Inspect Example Data\n",
    "\n",
    "\n",
    "Our data comes from the Numenta Anomaly Benchmark (NAB) NYC Taxi dataset [[1](https://github.com/numenta/NAB/blob/master/data/realKnownCause/nyc_taxi.csv)]. These data consists of the number of New York City taxi passengers over the course of six months aggregated into 30-minute buckets. We know, a priori, that there are anomalous events occurring during the NYC marathon, Thanksgiving, Christmas, New Year's day, and on the day of a snow storm.\n",
    "\n",
    "> [1] https://github.com/numenta/NAB/blob/master/data/realKnownCause/nyc_taxi.csv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%time\n",
    "\n",
    "import pandas as pd\n",
    "import urllib.request\n",
    "\n",
    "data_filename = 'nyc_taxi.csv'\n",
    "data_source = 'https://raw.githubusercontent.com/numenta/NAB/master/data/realKnownCause/nyc_taxi.csv'\n",
    "\n",
    "urllib.request.urlretrieve(data_source, data_filename)\n",
    "taxi_data = pd.read_csv(data_filename, delimiter=',')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Before training any models it is important to inspect our data, first. Perhaps there are some underlying patterns or structures that we could provide as \"hints\" to the model or maybe there is some noise that we could pre-process away. The raw data looks like this:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "taxi_data.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Human beings are visual creatures so let's take a look at a plot of the data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "import matplotlib\n",
    "import matplotlib.pyplot as plt\n",
    "matplotlib.rcParams['figure.dpi'] = 100\n",
    "\n",
    "taxi_data.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Human beings are also extraordinarily good at perceiving patterns. Note, for example, that something uncharacteristic occurs at around datapoint number 6000. Additionally, as we might expect with taxi ridership, the passenger count appears more or less periodic. Let's zoom in to not only examine this anomaly but also to get a better picture of what the \"normal\" data looks like."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "taxi_data[5500:6500].plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we see that the number of taxi trips taken is mostly periodic with one mode of length approximately 50 data points. In fact, the mode is length 48 since each datapoint represents a 30-minute bin of ridership count. Therefore, we expect another mode of length $336 = 48 \\times 7$, the length of a week. Smaller frequencies over the course of the day occur, as well.\n",
    "\n",
    "For example, here is the data across the day containing the above anomaly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "taxi_data[5952:6000]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Training\n",
    "\n",
    "***\n",
    "\n",
    "Next, we configure a SageMaker training job to train the Random Cut Forest (RCF) algorithm on the taxi cab data."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Hyperparameters\n",
    "\n",
    "Particular to a SageMaker RCF training job are the following hyperparameters:\n",
    "\n",
    "* **`num_samples_per_tree`** - the number randomly sampled data points sent to each tree. As a general rule, `1/num_samples_per_tree` should approximate the the estimated ratio of anomalies to normal points in the dataset.\n",
    "* **`num_trees`** - the number of trees to create in the forest. Each tree learns a separate model from different samples of data. The full forest model uses the mean predicted anomaly score from each constituent tree.\n",
    "* **`feature_dim`** - the dimension of each data point.\n",
    "\n",
    "In addition to these RCF model hyperparameters, we provide additional parameters defining things like the EC2 instance type on which training will run, the S3 bucket containing the data, and the AWS access role. Note that,\n",
    "\n",
    "* Recommended instance type: `ml.m4`, `ml.c4`, or `ml.c5`\n",
    "* Current limitations:\n",
    "  * The RCF algorithm does not take advantage of GPU hardware."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sagemaker import RandomCutForest\n",
    "\n",
    "session = sagemaker.Session()\n",
    "\n",
    "# specify general training job information\n",
    "rcf = RandomCutForest(role=execution_role,\n",
    "                      train_instance_count=1,\n",
    "                      train_instance_type='ml.m4.xlarge',\n",
    "                      data_location='s3://{}/{}/'.format(bucket, prefix),\n",
    "                      output_path='s3://{}/{}/output'.format(bucket, prefix),\n",
    "                      num_samples_per_tree=512,\n",
    "                      num_trees=50)\n",
    "\n",
    "# automatically upload the training data to S3 and run the training job\n",
    "rcf.fit(rcf.record_set(taxi_data.value.as_matrix().reshape(-1,1)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you see the message\n",
    "\n",
    "> `===== Job Complete =====`\n",
    "\n",
    "at the bottom of the output logs then that means training successfully completed and the output RCF model was stored in the specified output path. You can also view information about and the status of a training job using the AWS SageMaker console. Just click on the \"Jobs\" tab and select training job matching the training job name, below:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Training job name: {}'.format(rcf.latest_training_job.job_name))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Inference\n",
    "\n",
    "***\n",
    "\n",
    "A trained Random Cut Forest model does nothing on its own. We now want to use the model we computed to perform inference on data. In this case, it means computing anomaly scores from input time series data points.\n",
    "\n",
    "We create an inference endpoint using the SageMaker Python SDK `deploy()` function from the job we defined above. We specify the instance type where inference is computed as well as an initial number of instances to spin up. We recommend using the `ml.c5` instance type as it provides the fastest inference time at the lowest cost."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "rcf_inference = rcf.deploy(\n",
    "    initial_instance_count=1,\n",
    "    instance_type='ml.m4.xlarge',\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "Congratulations! You now have a functioning SageMaker RCF inference endpoint. You can confirm the endpoint configuration and status by navigating to the \"Endpoints\" tab in the AWS SageMaker console and selecting the endpoint matching the endpoint name, below: "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Endpoint name: {}'.format(rcf_inference.endpoint))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Data Serialization/Deserialization\n",
    "\n",
    "We can pass data in a variety of formats to our inference endpoint. In this example we will demonstrate passing CSV-formatted data. Other available formats are JSON-formatted and RecordIO Protobuf. We make use of the SageMaker Python SDK utilities `csv_serializer` and `json_deserializer` when configuring the inference endpoint."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sagemaker.predictor import csv_serializer, json_deserializer\n",
    "\n",
    "rcf_inference.content_type = 'text/csv'\n",
    "rcf_inference.serializer = csv_serializer\n",
    "rcf_inference.accept = 'application/json'\n",
    "rcf_inference.deserializer = json_deserializer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's pass the training dataset, in CSV format, to the inference endpoint so we can automatically detect the anomalies we saw with our eyes in the plots, above. Note that the serializer and deserializer will automatically take care of the datatype conversion from Numpy NDArrays.\n",
    "\n",
    "For starters, let's only pass in the first six datapoints so we can see what the output looks like."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "taxi_data_numpy = taxi_data.value.as_matrix().reshape(-1,1)\n",
    "print(taxi_data_numpy[:6])\n",
    "results = rcf_inference.predict(taxi_data_numpy[:6])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Computing Anomaly Scores\n",
    "\n",
    "Now, let's compute and plot the anomaly scores from the entire taxi dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "results = rcf_inference.predict(taxi_data_numpy)\n",
    "scores = [datum['score'] for datum in results['scores']]\n",
    "\n",
    "# add scores to taxi data frame and print first few values\n",
    "taxi_data['score'] = pd.Series(scores, index=taxi_data.index)\n",
    "taxi_data.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax1 = plt.subplots()\n",
    "ax2 = ax1.twinx()\n",
    "\n",
    "#\n",
    "# *Try this out* - change `start` and `end` to zoom in on the \n",
    "# anomaly found earlier in this notebook\n",
    "#\n",
    "start, end = 0, len(taxi_data)\n",
    "#start, end = 5500, 6500\n",
    "taxi_data_subset = taxi_data[start:end]\n",
    "\n",
    "ax1.plot(taxi_data_subset['value'], color='C0', alpha=0.8)\n",
    "ax2.plot(taxi_data_subset['score'], color='C1')\n",
    "\n",
    "ax1.grid(which='major', axis='both')\n",
    "\n",
    "ax1.set_ylabel('Taxi Ridership', color='C0')\n",
    "ax2.set_ylabel('Anomaly Score', color='C1')\n",
    "\n",
    "ax1.tick_params('y', colors='C0')\n",
    "ax2.tick_params('y', colors='C1')\n",
    "\n",
    "ax1.set_ylim(0, 40000)\n",
    "ax2.set_ylim(min(scores), 1.4*max(scores))\n",
    "fig.set_figwidth(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the anomaly score spikes where our eyeball-norm method suggests there is an anomalous data point as well as in some places where our eyeballs are not as accurate.\n",
    "\n",
    "Below we print and plot any data points with scores greater than 3 standard deviations (approx 99.9th percentile) from the mean score."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "score_mean = taxi_data['score'].mean()\n",
    "score_std = taxi_data['score'].std()\n",
    "score_cutoff = score_mean + 3*score_std\n",
    "\n",
    "anomalies = taxi_data_subset[taxi_data_subset['score'] > score_cutoff]\n",
    "anomalies"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The following is a list of known anomalous events which occurred in New York City within this timeframe:\n",
    "\n",
    "* `2014-11-02` - NYC Marathon\n",
    "* `2015-01-01` - New Year's Eve\n",
    "* `2015-01-27` - Snowstorm\n",
    "\n",
    "Note that our algorithm managed to capture these events along with quite a few others. Below we add these anomalies to the score plot."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ax2.plot(anomalies.index, anomalies.score, 'ko')\n",
    "fig"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "With the current hyperparameter choices we see that the three-standard-deviation threshold, while able to capture the known anomalies as well as the ones apparent in the ridership plot, is rather sensitive to fine-grained peruturbations and anomalous behavior. Adding trees to the SageMaker RCF model could smooth out the results as well as using a larger data set."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Stop and Delete the Endpoint\n",
    "\n",
    "Finally, we should delete the endpoint before we close the notebook.\n",
    "\n",
    "To do so execute the cell below. Alternately, you can navigate to the \"Endpoints\" tab in the SageMaker console, select the endpoint with the name stored in the variable `endpoint_name`, and select \"Delete\" from the \"Actions\" dropdown menu. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sagemaker.Session().delete_endpoint(rcf_inference.endpoint)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Epilogue\n",
    "\n",
    "---\n",
    "\n",
    "We used Amazon SageMaker Random Cut Forest to detect anomalous datapoints in a taxi ridership dataset. In these data the anomalies occurred when ridership was uncharacteristically high or low. However, the RCF algorithm is also capable of detecting when, for example, data breaks periodicity or uncharacteristically changes global behavior.\n",
    "\n",
    "Depending on the kind of data you have there are several ways to improve algorithm performance. One method, for example, is to use an appropriate training set. If you know that a particular set of data is characteristic of \"normal\" behavior then training on said set of data will more accurately characterize \"abnormal\" data.\n",
    "\n",
    "Another improvement is make use of a windowing technique called \"shingling\". This is especially useful when working with periodic data with known period, such as the NYC taxi dataset used above. The idea is to treat a period of $P$ datapoints as a single datapoint of feature length $P$ and then run the RCF algorithm on these feature vectors. That is, if our original data consists of points $x_1, x_2, \\ldots, x_N \\in \\mathbb{R}$ then we perform the transformation,\n",
    "\n",
    "```\n",
    "data = [[x_1],            shingled_data = [[x_1, x_2, ..., x_{P}],\n",
    "        [x_2],    --->                     [x_2, x_3, ..., x_{P+1}],\n",
    "        ...                                ...\n",
    "        [x_N]]                             [x_{N-P}, ..., x_{N}]]\n",
    "\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "def shingle(data, shingle_size):\n",
    "    num_data = len(data)\n",
    "    shingled_data = np.zeros((num_data-shingle_size, shingle_size))\n",
    "    \n",
    "    for n in range(num_data - shingle_size):\n",
    "        shingled_data[n] = data[n:(n+shingle_size)]\n",
    "    return shingled_data\n",
    "\n",
    "# single data with shingle size=48 (one day)\n",
    "shingle_size = 48\n",
    "prefix_shingled = 'sagemaker/randomcutforest_shingled'\n",
    "taxi_data_shingled = shingle(taxi_data.values[:,1], shingle_size)\n",
    "print(taxi_data_shingled)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We create a new training job and and inference endpoint. (Note that we cannot re-use the endpoint created above because it was trained with one-dimensional data.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "session = sagemaker.Session()\n",
    "\n",
    "# specify general training job information\n",
    "rcf = RandomCutForest(role=execution_role,\n",
    "                      train_instance_count=1,\n",
    "                      train_instance_type='ml.m4.xlarge',\n",
    "                      data_location='s3://{}/{}/'.format(bucket, prefix_shingled),\n",
    "                      output_path='s3://{}/{}/output'.format(bucket, prefix_shingled),\n",
    "                      num_samples_per_tree=512,\n",
    "                      num_trees=50)\n",
    "\n",
    "# automatically upload the training data to S3 and run the training job\n",
    "rcf.fit(rcf.record_set(taxi_data_shingled))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sagemaker.predictor import csv_serializer, json_deserializer\n",
    "\n",
    "rcf_inference = rcf.deploy(\n",
    "    initial_instance_count=1,\n",
    "    instance_type='ml.m4.xlarge',\n",
    ")\n",
    "\n",
    "rcf_inference.content_type = 'text/csv'\n",
    "rcf_inference.serializer = csv_serializer\n",
    "rcf_inference.accept = 'appliation/json'\n",
    "rcf_inference.deserializer = json_deserializer"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using the above inference endpoint we compute the anomaly scores associated with the shingled data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Score the shingled datapoints\n",
    "results = rcf_inference.predict(taxi_data_shingled)\n",
    "scores = np.array([datum['score'] for datum in results['scores']])\n",
    "\n",
    "# compute the shingled score distribution and cutoff and determine anomalous scores\n",
    "score_mean = scores.mean()\n",
    "score_std = scores.std()\n",
    "score_cutoff = score_mean + 3*score_std\n",
    "\n",
    "anomalies = scores[scores > score_cutoff]\n",
    "anomaly_indices = np.arange(len(scores))[scores > score_cutoff]\n",
    "\n",
    "print(anomalies)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, we plot the scores from the shingled data on top of the original dataset and mark the score lying above the anomaly score threshold."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax1 = plt.subplots()\n",
    "ax2 = ax1.twinx()\n",
    "\n",
    "#\n",
    "# *Try this out* - change `start` and `end` to zoom in on the \n",
    "# anomaly found earlier in this notebook\n",
    "#\n",
    "start, end = 0, len(taxi_data)\n",
    "taxi_data_subset = taxi_data[start:end]\n",
    "\n",
    "ax1.plot(taxi_data['value'], color='C0', alpha=0.8)\n",
    "ax2.plot(scores, color='C1')\n",
    "ax2.scatter(anomaly_indices, anomalies, color='k')\n",
    "\n",
    "ax1.grid(which='major', axis='both')\n",
    "ax1.set_ylabel('Taxi Ridership', color='C0')\n",
    "ax2.set_ylabel('Anomaly Score', color='C1')\n",
    "ax1.tick_params('y', colors='C0')\n",
    "ax2.tick_params('y', colors='C1')\n",
    "ax1.set_ylim(0, 40000)\n",
    "ax2.set_ylim(min(scores), 1.4*max(scores))\n",
    "fig.set_figwidth(10)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We see that with this particular shingle size, hyperparameter selection, and anomaly cutoff threshold that the shingled approach more clearly captures the major anomalous events: the spike at around t=6000 and the dips at around t=9000 and t=10000. In general, the number of trees, sample size, and anomaly score cutoff are all parameters that a data scientist may need experiment with in order to achieve desired results. The use of a labeled test dataset allows the used to obtain common accuracy metrics for anomaly detection algorithms. For more information about Amazon SageMaker Random Cut Forest see the [AWS Documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/randomcutforest.html)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sagemaker.Session().delete_endpoint(rcf_inference.endpoint)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "conda_python3",
   "language": "python",
   "name": "conda_python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  },
  "notice": "Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.  Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License."
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
